package com.ktjiaoyu.crm.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjiaoyu.crm.config.shiro.MyShiroRealm;
import com.ktjiaoyu.crm.pojo.Right;
import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.redis.RedisTemplateUtil;
import com.ktjiaoyu.crm.service.RightService;
import com.ktjiaoyu.crm.service.RoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

@Controller
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @Autowired
    private RightService rightService;


    /**
     * 获取所有角色信息
     * @return
     */
    @RequestMapping(value = "/role/json")
    @ResponseBody
    public List<Role> findAllRoles(){

        //查询列表时从redis中先找，如果没有再查数据库
        Object object = redisTemplateUtil.get("allRoleList");
        if(null != object){
            //redis中有数据，直接返回
            return (List<Role>)object;
        }

        //查询所有角色信息
        List<Role> roles = roleService.list();
        //将数据库查询的数据缓存进Redis
        redisTemplateUtil.set("allRoleList",roles);
        return roles;
    }


    /**
     * 角色列表
     * @param model
     * @param roleName
     * @param pageIndex
     * @return
     */
    @RequestMapping(value = "/role/list")
    public String list(Model model, String roleName, @RequestParam(value = "pageIndex",defaultValue = "1") Integer pageIndex){
        //实例化Page对象
        Page<Role> page = new Page<>(pageIndex,5);
        //查询角色列表
        page = roleService.selectRolePages(page,roleName);
        model.addAttribute("roleName",roleName);
        model.addAttribute("rolePage",page);
        return "role/list";
    }

    /**
     * 编辑角色（包括角色信息及对应的权限）
     */
    @RequestMapping("/role/edit")
    public String edit(Model model, Long roleId) {
        //根据角色ID查询角色信息
        Role role = roleService.getById(roleId);

        //根据角色ID查询角色所拥有权限
        List<Right> roleRights = rightService.getRightsByRoleId(role.getRoleId());
        // 获得所有权限数据展示到页面供选择
        List<Right> rights = rightService.list();
        // 设置到作用域
        model.addAttribute("rights", rights);
        // 设置当前要修改的角色的信息及对应的权限到作用域
        model.addAttribute("role", role);
        model.addAttribute("roleRights",roleRights);
        return "role/edit";
    }

    /**
     * 执行新增或修改角色
     */
    @PostMapping("/role/save")
    public String save(Role role, String[] rightCodes) {
        // 在没有选择任何权限时，容错处理
        rightCodes = rightCodes == null ? new String[0] : rightCodes;
        // 打印 最终为角色选择的权限，复选框使用字符串数组接收
        System.out.println(new JSONArray(Arrays.asList(rightCodes)).toString());

        // 如果角色的启用状态为null则设置为0
        if (role != null && role.getRoleFlag() == null) {
            role.setRoleFlag(0);
        }
        // 如果有带ID就修改，没有带ID则添加
        roleService.saveRoleAndRight(role, rightCodes);
        // 清空权限缓存
        //RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        //MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();

        return "redirect:/role/list"; // 重定向
    }
}
